package me.helllp.dake.generator.engine.service;

import com.squareup.javapoet.AnnotationSpec;
import freemarker.template.TemplateException;
import lombok.Getter;
import lombok.Setter;
import me.helllp.dake.generator.config.GeneratorEngineConfiguration;
import me.helllp.dake.generator.engine.JavaFileGenerator;
import me.helllp.dake.generator.meta.ProjectMetaData;
import me.helllp.dake.generator.utils.GenClassUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Getter
@Setter
public class ApplicationGenerator extends JavaFileGenerator {
    private static final String APPLICATION_START_CLASS = "ApplicationStarter";

    public ApplicationGenerator(ProjectMetaData projectMetaData) {
        super(projectMetaData);
    }

    @Override
    public void initGenerator(GeneratorEngineConfiguration engineConfiguration) throws TemplateException, IOException, InvocationTargetException, IllegalAccessException {
        super.initGenerator(engineConfiguration);
        this.setFileName(APPLICATION_START_CLASS);
        this.setTypeSpec(GenClassUtils.makeApplicationClass(APPLICATION_START_CLASS));
    }

    @Override
    public void generator() throws IOException, TemplateException {
        List<AnnotationSpec> list = Optional.ofNullable(getProjectMetaData().getThirdComponents()).orElse(Collections.emptyList())
                .stream().map(data -> data.toAnnotations(getProjectMetaData())).flatMap(Collection::stream).collect(Collectors.toList());
        this.setTypeSpec(this.getTypeSpec().toBuilder().addAnnotations(list).build());

        super.generator();
    }
}
